package com.project.nimsen.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.stereotype.Repository;

import com.project.nimsen.constant.NimsenConstant;
import com.project.nimsen.dao.IBaseDao;
import com.project.nimsen.dto.ArchivesDto;
import com.project.nimsen.entity.Archivefile;
import com.project.nimsen.entity.Archives;
import com.project.nimsen.entity.Archivescolumn;
import com.project.nimsen.entity.Coltype;
import com.project.nimsen.entity.Filearchivrelation;
import com.project.nimsen.entity.Urlinfo;
import com.project.nimsen.service.IArchivesService;
import com.project.nimsen.service.IColtypeService;
import com.project.nimsen.service.IFilearchivrelationService;
import com.project.jdbc.dao.IBaseJdbcDao;
import com.project.jdbc.service.BaseServiceImpl;
import com.project.jdbc.utils.Finder;
import com.project.jdbc.utils.Page;
@Repository("archivesService")
public class ArchivesServiceImpl extends BaseServiceImpl implements IArchivesService {
	@Resource
	IBaseDao baseDao;
	@Resource
	IColtypeService coltypeService;
	protected IBaseJdbcDao getBaseDao() {
		return baseDao;
	}
	@Resource
	IFilearchivrelationService relationService;
	public List<Map<String, Object>> finder(ArchivesDto dto) throws Exception {
		Finder finder = new Finder("select arc.id as id,arc.title as title,arc.shottitle"
			+ " as shottitle,arc.author as author,arc.createTime as createTime,col.colname,"
			+ " us.username as noteusername from archives as arc left join archivescolumn "
			+ "as aco on arc.id=aco.archives left join coltype as col on aco.coltypeid=col.id"
			+ " left join user as us on arc.createUser=us.id where arc.active!=1 and "
			+ "aco.active!=1 and us.id!=1");
		//查询类型设置
		if("zhu".equals(dto.getFinderType()))
			finder.append(" and aco.mancol=0");
		if("fu".equals(dto.getFinderType()))
			finder.append(" and aco.mancol=1");
		if(StringUtils.isNotBlank(dto.getColtypeid())){
			finder.append(" and aco.coltypeid=:coltypeid");
			finder.setParam("coltypeid", dto.getColtypeid());
		}
		if(StringUtils.isNotBlank(dto.getValtitle())){
			finder.append(" and arc.title=:qutitle");
			finder.setParam("qutitle", dto.getValtitle());
		}
		if(StringUtils.isNotBlank(dto.getValid())){
			finder.append(" and arc.id!=:valid");
			finder.setParam("valid", dto.getValid());
		}
		if(StringUtils.isNotBlank(dto.getCreateuser())){
			finder.append(" and arc.createUser=:createUser");
			finder.setParam("createUser", dto.getCreateuser());
		}
		finder.append(" order by arc.createTime desc");
		if(dto.getPage()!=null)
			return baseDao.queryForList(finder, dto.getPage());
		return baseDao.queryForList(finder);
	}
	public boolean save(ArchivesDto dto) throws Exception {
		//操作的实体
		Archives arch = dto.getArch();
		String arch_id = null;
		//保存文章信息
		if(StringUtils.isNotBlank(arch.getId())){
			arch_id = arch.getId();
			baseDao.update(arch);
		}else{
			Object arch_id_obj = baseDao.saveEntity(arch);
			arch_id = arch_id_obj.toString();
		}
		//处理主栏目副栏目信息
		List<Archivescolumn> columns = new ArrayList<Archivescolumn>();
		Archivescolumn zhucol = new Archivescolumn();
		zhucol.setActive(0);
		zhucol.setArchives(arch_id);
		//得到栏目编号
		Coltype colzhu = coltypeService.findEntityByNumer(dto.getZhucolnameid(), null);
		zhucol.setColtypeid(colzhu.getId());
		zhucol.setCreateTime(new Date());
		zhucol.setCreateUser(dto.getCurrUserId());
		zhucol.setMancol(0);
		columns.add(zhucol);
		//如果没有副栏目则直接保存缩略图与主栏目信息
		if(StringUtils.isBlank(dto.getFucolnameid())){
			if(!saveMcroimgCol(columns, arch_id, dto))
				return false;
			return saveUrlList(arch_id, dto);
		}
		//把副栏目添加到list里
		String [] fucolumnids = StringUtils.split(dto.getFucolnameid(), ",");
		int countfucols = fucolumnids.length;
		for(int i=0;i<countfucols;i++){
			Archivescolumn fucol = new Archivescolumn();
			fucol.setActive(0);
			fucol.setArchives(arch_id);
			//得到栏目编号
			Coltype colfu = coltypeService.findEntityByNumer(fucolumnids[i], null);
			fucol.setColtypeid(colfu.getId());
			fucol.setCreateTime(new Date());
			fucol.setCreateUser(dto.getCurrUserId());
			fucol.setMancol(1);
			columns.add(fucol);
		}
		if(!saveMcroimgCol(columns, arch_id, dto))
			return false;
		return saveUrlList(arch_id, dto);
	}
	/**
	 * 保存url集合信息
	 * */
	private boolean saveUrlList(String arch_id, ArchivesDto dto)throws Exception{
		//以前文章所对应 的url信息
		Finder update = new Finder("update urlinfo set active=1 where urloutable="
			+ ":urloutable and active=0 and urloutid=:urloutid");
		update.setParam("urloutid", arch_id);
		update.setParam("urloutable", NimsenConstant.ARCHIVES_URL_LIST);
		baseDao.update(update);
		
		String urls = dto.getUrlist();
		if(StringUtils.isBlank(urls))
			return true;
		String [] strurls = StringUtils.split(urls, "§");
		if(strurls==null||strurls.length<1)
			return true;
		Date nowDate = new Date();
		//组装实体类
		List<Urlinfo> urlist = new ArrayList<Urlinfo>();
		for(String url : strurls){
			if(StringUtils.isBlank(url))
				continue;
			Urlinfo urlinfo = new Urlinfo();
			urlinfo.setActive(0);
			urlinfo.setCreateTime(nowDate);
			urlinfo.setCreateUser(dto.getCurrUserId());
			urlinfo.setUrl(url);
			urlinfo.setUrloutable(NimsenConstant.ARCHIVES_URL_LIST);
			urlinfo.setUrloutid(arch_id);
			urlist.add(urlinfo);
		}
		if(CollectionUtils.isEmpty(urlist))
			return true;
		baseDao.saveList(urlist);
		return true;
	}
	/**
	 * 保存一个文章的栏目信息与图片信息
	 * */
	private boolean saveMcroimgCol(List<Archivescolumn> columns,String arch_id,ArchivesDto dto)throws Exception{
		Date nowDate = new Date();
		//把之前关连的栏目删除
		Finder colupdate = new Finder("update archivescolumn set active=1 where archives=:archives and active=0");
		colupdate.setParam("archives", arch_id);
		baseDao.update(colupdate);
		//添加新栏目
		baseDao.saveList(columns);
		//保存缩略图信息
		Filearchivrelation rela = relationService.findByValue(NimsenConstant.FILE_RELATION_MICROIMG);
		//把之前关连的缩略图删除
		Finder imgupdate = new Finder("update archivefile set active=1 where archivesid=:archives and active!=1"
				+ " and relationid=:relationid");
		imgupdate.setParam("relationid", rela.getId());
		imgupdate.setParam("archives", arch_id);
		baseDao.update(imgupdate);
		if(StringUtils.isNotBlank(dto.getMicroimgid())){
			//添加缩略图
			Archivefile arfile = new Archivefile();
			arfile.setActive(0);
			arfile.setArchivesid(arch_id);
			arfile.setCreateTime(nowDate);
			arfile.setCreateUser(dto.getCurrUserId());
			arfile.setDescs("文章的缩略图");
			arfile.setFileid(dto.getMicroimgid());
			arfile.setRelationid(rela.getId());
			baseDao.saveEntity(arfile);
		}
		//保存图片集合
		Filearchivrelation reimglist = relationService.findByValue(NimsenConstant.FILE_RELATION_IMGLIST);
		//把之前关连的缩略图删除
		Finder imglistupdate = new Finder("update archivefile set active=1 where archivesid=:archives and active!=1"
				+ " and relationid=:relationid");
		imglistupdate.setParam("relationid", reimglist.getId());
		imglistupdate.setParam("archives", arch_id);
		baseDao.update(imglistupdate);
		String imglist = dto.getImglist();
		if(StringUtils.isBlank(imglist))
			return true;
		String[] list = StringUtils.split(imglist, "§");
		if(list==null||list.length<1)
			return true;
		List<Archivefile> arfiles = new ArrayList<Archivefile>();
		for(String imginfo : list){
			if(StringUtils.isBlank(imginfo))
				continue;
			String [] infos = StringUtils.split(imginfo,"※");
			if(infos==null||infos.length<1)
				continue;
			//保存集合图片集合
			Archivefile arfile = new Archivefile();
			arfile.setActive(0);
			arfile.setArchivesid(arch_id);
			arfile.setCreateTime(nowDate);
			arfile.setCreateUser(dto.getCurrUserId());
			arfile.setDescs(infos[1]);
			arfile.setFileid(infos[0]);
			arfile.setRelationid(reimglist.getId());
			arfiles.add(arfile);
		}
		if(CollectionUtils.isEmpty(arfiles))
			return true;
		return baseDao.saveList(arfiles)!=null;
	}
	public Map<String, Object> findById(String id) throws Exception {
		return baseDao.queryForObject(findOneByid(id));
	}
	private Finder findOneByid(String id){
		Finder finder = new Finder("select id,title,shottitle,tag,sourceurl,author,summary,"
			+ "htmlcontent,textcontent,createUser,createTime,updateTime,active from archives"
			+ " where active!=1 and id=:id");
		finder.setParam("id", id);
		return finder;
	}
	public Archives findEntityById(String id) throws Exception {
		return baseDao.queryForObject(findOneByid(id), Archives.class);
	}
	public List<Map<String, Object>> findTagByDto(ArchivesDto dto)
			throws Exception {
		Finder finder = new Finder("select arch.id,arch.title,arch.shottitle,arch.tag,arch."
			+ "sourceurl,arch.author,arch.summary");
		//是否显示html标签内容
		if("true".equals(dto.getHtmlcontent()))
			finder.append(",arch.htmlcontent");
		//是否显示text内容
		if("true".equals(dto.getHtmlcontent()))
			finder.append(",arch.textcontent");
		finder.append(",arch.createTime,arch.updateTime from archives as arch "
			+ "where arch.active!=1 and arch.id in (select archives from archivescolumn"
			+ " where active!=1 and coltypeid in (select id from coltype where active!=1"
			+ "  and number=:number");
		finder.setParam("number", dto.getColnumber());
		if(StringUtils.isNotBlank(dto.getSiteid())){
			finder.append(" and siteid=:siteid");
			finder.setParam("siteid", dto.getSiteid());
		}
		finder.append(")) order by");
		//排序字段
		if("UPDATE".equals(dto.getOrderfile())){
			finder.append(" arch.updateTime");
		}else
			finder.append(" arch.createTime");
		//排序方式
		if("DESC".equals(dto.getOrder())){
			finder.append(" desc");
		}else
			finder.append(" asc");
		//如果查询所有的内容
		if(dto.getNum()<1&&dto.getPagesize()<1)
			return baseDao.queryForList(finder);
		//分页信息设置
		Page page = new Page(dto.getPageIndex());
		if(dto.getNum()>0)
			page.setPageSize(dto.getNum());
		else
			page.setPageSize(dto.getPagesize());
		List<Map<String, Object>> list = baseDao.queryForList(finder, page);
		dto.setPage(page);
		return list;
	}
	public boolean deleteByDto(ArchivesDto dto) throws Exception {
		if(dto==null)
			return false;
		Finder colFinder = new Finder("update archivescolumn set active=1 where active!=1");
		if(StringUtils.isNotBlank(dto.getId())){
			colFinder.append(" and archives=:archives");
			colFinder.setParam("archives", dto.getId());
		}
		baseDao.update(colFinder);
		
		Finder arcFinder = new Finder("update archives set active=1 where active!=1");
		if(StringUtils.isNotBlank(dto.getId())){
			arcFinder.append(" and id=:id");
			arcFinder.setParam("id", dto.getId());
		}
		baseDao.update(arcFinder);
		return false;
	}
}
